using ZYFramework.AudioSystem;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;

namespace ZYFramework.AudioSystem.Samples
{
    /// <summary>
    /// 音频系统高级功能样例
    /// 演示音量调节、优先级控制、BGM切换等高级功能
    /// </summary>
    public class AudioSystemAdvancedExample : MonoBehaviour
    {
        [Header("UI组件（可选）")]
        [SerializeField] private Slider bgmVolumeSlider;
        [SerializeField] private Slider sfxVolumeSlider;
        [SerializeField] private Toggle muteToggle;
        [SerializeField] private Button switchBGMButton;

        [Header("测试设置")]
        [SerializeField] private string bgm1Name = "GameMain";
        [SerializeField] private string bgm2Name = "SceneTown";

        private float _bgmVolume = 1f;
        private float _sfxVolume = 1f;
        private bool _isMuted = false;
        private bool _isBGM1Playing = true;

        private void Start()
        {
            // 初始化UI
            if (bgmVolumeSlider != null)
            {
                bgmVolumeSlider.value = _bgmVolume;
                bgmVolumeSlider.onValueChanged.AddListener(OnBGMVolumeChange);
            }

            if (sfxVolumeSlider != null)
            {
                sfxVolumeSlider.value = _sfxVolume;
                sfxVolumeSlider.onValueChanged.AddListener(OnSFXVolumeChange);
            }

            if (muteToggle != null)
            {
                muteToggle.isOn = _isMuted;
                muteToggle.onValueChanged.AddListener(OnMuteToggle);
            }

            if (switchBGMButton != null)
            {
                switchBGMButton.onClick.AddListener(OnSwitchBGM);
            }

            // 初始播放BGM
            AudioManager_Entity.Instance.PlayBGM(bgm1Name);
        }

        private void Update()
        {
            // 键盘测试
            if (Input.GetKeyDown(KeyCode.Q))
            {
                // 增加BGM音量
                _bgmVolume = Mathf.Clamp01(_bgmVolume + 0.1f);
                SetBGMVolume(_bgmVolume);
            }

            if (Input.GetKeyDown(KeyCode.A))
            {
                // 减少BGM音量
                _bgmVolume = Mathf.Clamp01(_bgmVolume - 0.1f);
                SetBGMVolume(_bgmVolume);
            }

            if (Input.GetKeyDown(KeyCode.W))
            {
                // 增加SFX音量
                _sfxVolume = Mathf.Clamp01(_sfxVolume + 0.1f);
                SetSFXVolume(_sfxVolume);
            }

            if (Input.GetKeyDown(KeyCode.S))
            {
                // 减少SFX音量
                _sfxVolume = Mathf.Clamp01(_sfxVolume - 0.1f);
                SetSFXVolume(_sfxVolume);
            }

            if (Input.GetKeyDown(KeyCode.M))
            {
                // 切换静音
                _isMuted = !_isMuted;
                SetMute(_isMuted);
            }

            if (Input.GetKeyDown(KeyCode.B))
            {
                // 切换BGM
                OnSwitchBGM();
            }

            if (Input.GetKeyDown(KeyCode.P))
            {
                // 测试优先级控制
                TestPriorityControl();
            }
        }

        /// <summary>
        /// 设置BGM音量
        /// </summary>
        private void SetBGMVolume(float volume)
        {
            AudioManager_Entity.Instance.SetGlobalVolume(AudioType.BGM, volume);
            _bgmVolume = volume;

            if (bgmVolumeSlider != null)
            {
                bgmVolumeSlider.value = volume;
            }

            Debug.Log($"[高级示例] BGM音量: {volume:F2}");
        }

        /// <summary>
        /// 设置SFX音量
        /// </summary>
        private void SetSFXVolume(float volume)
        {
            AudioManager_Entity.Instance.SetGlobalVolume(AudioType.SFX_2D, volume);
            AudioManager_Entity.Instance.SetGlobalVolume(AudioType.SFX_3D, volume);
            _sfxVolume = volume;

            if (sfxVolumeSlider != null)
            {
                sfxVolumeSlider.value = volume;
            }

            Debug.Log($"[高级示例] SFX音量: {volume:F2}");
        }

        /// <summary>
        /// 设置静音
        /// </summary>
        private void SetMute(bool isMute)
        {
            AudioManager_Entity.Instance.MuteAudio(AudioType.BGM, isMute);
            _isMuted = isMute;

            if (muteToggle != null)
            {
                muteToggle.isOn = isMute;
            }

            Debug.Log($"[高级示例] BGM静音: {isMute}");
        }

        /// <summary>
        /// UI回调：BGM音量变化
        /// </summary>
        private void OnBGMVolumeChange(float value)
        {
            SetBGMVolume(value);
        }

        /// <summary>
        /// UI回调：SFX音量变化
        /// </summary>
        private void OnSFXVolumeChange(float value)
        {
            SetSFXVolume(value);
        }

        /// <summary>
        /// UI回调：静音切换
        /// </summary>
        private void OnMuteToggle(bool isOn)
        {
            SetMute(isOn);
        }

        /// <summary>
        /// UI回调：切换BGM
        /// </summary>
        private async void OnSwitchBGM()
        {
            _isBGM1Playing = !_isBGM1Playing;
            string bgmName = _isBGM1Playing ? bgm1Name : bgm2Name;

            await AudioManager_Entity.Instance.PlayBGMAsync(bgmName);
            Debug.Log($"[高级示例] 切换BGM: {bgmName}");
        }

        /// <summary>
        /// 测试优先级控制
        /// </summary>
        [ContextMenu("测试优先级控制")]
        public async void TestPriorityControl()
        {
            Debug.Log("[高级示例] 开始优先级测试：先播放多个低优先级音效，然后播放高优先级音效");

            // 播放多个低优先级音效（填满对象池）
            for (int i = 0; i < 5; i++)
            {
                var lowParam = AudioPlayParams.Create2D(
                    volume: 0.5f,
                    priority: AudioPriority.Low
                );
                AudioManager_Entity.Instance.PlaySFX2DAsync("TestSFX", lowParam).Forget();
                await UniTask.Delay(100);
            }

            Debug.Log("[高级示例] 已播放5个低优先级音效");

            await UniTask.Delay(500);

            // 播放高优先级音效（应该能打断低优先级音效）
            var highParam = AudioPlayParams.Create2D(
                volume: 1f,
                priority: AudioPriority.High
            );
            await AudioManager_Entity.Instance.PlaySFX2DAsync("TestSFX", highParam);
            Debug.Log("[高级示例] 播放高优先级音效（应该能成功播放）");
        }

        /// <summary>
        /// 测试调试监控
        /// </summary>
        [ContextMenu("测试调试监控")]
        public void TestDebugMonitor()
        {
            AudioManager_Entity.Instance.PrintDebugInfo();
        }

        private void OnGUI()
        {
            GUILayout.BeginArea(new Rect(10, 10, 400, 300));
            GUILayout.Label("=== 音频系统高级功能示例 ===");
            GUILayout.Label($"BGM音量: {_bgmVolume:F2} (Q/A增减)");
            GUILayout.Label($"SFX音量: {_sfxVolume:F2} (W/S增减)");
            GUILayout.Label($"静音: {_isMuted} (M切换)");
            GUILayout.Label($"当前BGM: {(_isBGM1Playing ? bgm1Name : bgm2Name)} (B切换)");
            GUILayout.Label("按 P - 测试优先级控制");
            GUILayout.Label("按 D - 打印调试信息");

            if (Input.GetKeyDown(KeyCode.D))
            {
                TestDebugMonitor();
            }

            GUILayout.EndArea();
        }
    }
}
